# -*- coding: utf-8 -*-
# filename: handle.py


import json
import re
import random
import urllib
import requests
from lottery.view import mysql_util

def getSMS(request):
    try:
        webData = json.loads(request.body)
        numbers = webData['mobile']
        pattern1 = re.compile(r'[0-9]{11}')
        if pattern1.match(numbers):
            data = {"accesskey":"3565","secretkey":"56f52b8b8a8bde3a8cd4180ee471640dcf69a1ae"}
            data['mobile'] = numbers
            smscode = getRandomCode()
            data['content'] = "验证码: "+ smscode+"【西安交大MEM2018年会组委会】"
            url = "http://imlaixin.cn/Api/send/data/json?"
            r = requests.post(url + urllib.urlencode(data))
            rd = eval(r.text.replace('null', '"null"'))
            if rd['result'] == "01":
                result = {'result': True, 'msg': '已发送'}
                conn = mysql_util.getconn()
                cr = conn.execute('select * from checks where mobile= %s ' % str(numbers))
                if cr == 0:
                    param = (numbers, smscode)
                    conn.execute('insert into checks(mobile,smscode) values(%s,%s)', param)
                else:
                    param = (str(numbers),smscode)
                    conn.execute('update checks set smscode=%s where mobile=%s',param)
                conn.close()
                return json.dumps(result)
            else:
                result = {'result': False, 'msg': '发送失败'}
                return json.dumps(result)
    except Exception as e:
        return e.args

def getRandomCode():
    code_list = []
    for i in range(6):
        code_list.append(str(random.randint(0,9)))
    return "".join(code_list)



